package org.springframework.security.util;

import com.je.core.constants.login.LoginKeyType;
import com.je.core.util.SecurityUserHolder;
import com.je.core.util.StringUtil;
import com.je.core.util.WebUtils;
import net.sf.json.JSONObject;
import org.springframework.security.ui.AbstractProcessingFilter;
import org.springframework.security.ui.logout.LogoutFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * @author Luke Taylor
 * @version $Id: RedirectUtils.java 2217 2007-10-27 00:45:30Z luke_t $
 */
public abstract class RedirectUtils {
	//~ Constructors ===================================================================================================

	private RedirectUtils() {
	}

	//~ Methods ========================================================================================================

	/**
	 * Encapsulates the redirect logic used in classes like {@link AbstractProcessingFilter} and {@link LogoutFilter}.
	 *
	 * @param request the incoming request
	 * @param response the response to redirect
	 * @param url the target url to redirect to
	 * @param useRelativeContext if true, causes any redirection URLs to be calculated minus the protocol
	 * and context path.
	 *
	 * @see AbstractProcessingFilter#setUseRelativeContext(boolean)
	 */
	public static final void sendRedirect(HttpServletRequest request,
										  HttpServletResponse response,
										  String url,
										  boolean useRelativeContext) throws IOException {
		String finalUrl;
		if (!url.startsWith("http://") && !url.startsWith("https://")) {
			if (useRelativeContext) {
				finalUrl = url;
			}
			else {
				finalUrl = request.getContextPath() + url;
			}
		}
		else if (useRelativeContext) {
			// Calculate the relative URL from the fully qualifed URL, minus the protocol and base context.
			int len = request.getContextPath().length();
			int index = url.indexOf(request.getContextPath()) + len;
			finalUrl = url.substring(index);

			if (finalUrl.length() > 1 && finalUrl.charAt(0) == '/') {
				finalUrl = finalUrl.substring(1);
			}
		}
		else {
			finalUrl = url;
		}
		String returnUrl=response.encodeRedirectURL(finalUrl);
		if(StringUtil.getDefaultValue(WebUtils.getSysVar("JE_CORE_PHONE"),"1").equals(request.getParameter("phone")) ||
				"PC".equals(request.getParameter("clientType")) || "MT".equals(request.getParameter("clientType"))){
			String callbackName=request.getParameter("callback");
			if(StringUtil.isNotEmpty(returnUrl) && returnUrl.indexOf("/app/index.action")!=-1){
				String jeKeyParam="";
				if("JEKEY".equals(request.getParameter("loginType"))){
					jeKeyParam=request.getSession().getAttribute(LoginKeyType.__JEKEYPARAMS__)+"";
				}
				JSONObject returnObj=new JSONObject();
				returnObj.put("success", true);
				JSONObject obj=new JSONObject();
				obj.put("sessionId", request.getSession().getId());
				obj.put("loginUserCode", request.getParameter("j_username"));
				obj.put("jeKeyParam", jeKeyParam);
				returnObj.put("obj", obj);
				if(StringUtil.isNotEmpty(callbackName)){
					toWrite(response, callbackName+"("+returnObj.toString()+")");
				}else{
					toWrite(response,returnObj.toString());
				}
			}else{
				String errorMsg="登录失败";
				Exception e=(Exception) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
				if(e!=null){
					errorMsg=SecurityUserHolder.getLoginErrorCode(e);
				}
				if(StringUtil.isNotEmpty(callbackName)){
					toWrite(response,callbackName+"({\"success\":false,\"obj\":\""+errorMsg+"\"})");
				}else{
					toWrite(response,"{\"success\":false,\"obj\":\""+errorMsg+"\"}");
				}
			}
		}else{
			Exception e = (Exception)request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
			if ((e != null) && (!"/app/index.action".equals(returnUrl))){
				String errorType = e.getMessage();
				if ((StringUtil.isNotEmpty(errorType).booleanValue()) && (errorType.startsWith("NOREGISTER")) && (StringUtil.isEmpty(request.getParameter("j_username")).booleanValue()))
				{
					String[] vals = errorType.split("@")[1].split("#");
					returnUrl = "/JE/resource/login/register/account2.jsp?access_token=" + vals[0] + "&openId=" + vals[1] + "&type=" + vals[3] + "&unionId=" + vals[2];
				}
			}else if(StringUtil.isNotEmpty(returnUrl) && returnUrl.indexOf("/app/index.action")!=-1){
				String jeKeyParam="";
				if("JEKEY".equals(request.getParameter("loginType"))){
					jeKeyParam=(jeKeyParam.indexOf("?")!=-1?"&":"?")+request.getSession().getAttribute(LoginKeyType.__JEKEYPARAMS__)+"";
				}
				returnUrl=returnUrl+jeKeyParam;
			}
//			response.sendRedirect(returnUrl);
		}
	}
	/**
	 * 将一段字符串写入response.writer，默认为UTF-8编码
	 * @param contents
	 * @throws IOException
	 */
	public static void toWrite(HttpServletResponse response,String contents) {
		response.setContentType("text/javascript");
		if(null != response) {
			Writer writer = null;
			try {
				response.setCharacterEncoding("utf-8");
				writer =  response.getWriter();
				writer.write(contents);
			} catch (IOException e) {
//				logger.error(e.getMessage());
			}finally{
				try {
					writer.flush();
					writer.close();
					response.flushBuffer();
				} catch (IOException e) {
//					logger.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}
}
